package demo.proxy;


import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : feixiang.li
 * @since : 2025-09-18 14:01
 */
public class Complier {



    public static void compile(File javaFile) {

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = null;
        try {
            fileManager = compiler.getStandardFileManager(null, null, null);
            // 获取要编译的文件对象
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFile);
            // 设置编译选项（可选，例如指定输出目录。我这里由于目录结构问题，写的demo1）
//            List<String> options = List.of("-d", "./target/classes");
            List<String> options = List.of("-d", "./demo1/target/classes");
            // 创建编译任务
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, options, null, compilationUnits);
            // 执行编译
            boolean result = task.call();

            if (result) {
                System.out.println("编译成功！");
            } else {
                System.out.println("编译失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileManager != null) {
                    fileManager.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
